package com.cs.pk.codestriker;

import java.io.IOException;
import java.io.OutputStream;

import org.eclipse.swt.SWT;

import com.cs.pk.interfaces.PopulateInterface;
import com.cs.pk.utils.ClearCaseException;
import com.cs.pk.utils.StreamReader;
import com.cs.pk.utils.Util;
import com.cs.pk.utils.UtilRepository;

public abstract class AbstractPopulateList implements PopulateInterface{

	String result = null;
	protected Object component = null;
	public AbstractPopulateList(Object component) {
		this.component = component;
	}
	
	public synchronized String runBatFile(String cmds[]) throws IOException, InterruptedException, ClearCaseException {

		Process process;
		ProcessBuilder builder = null;

		builder = new ProcessBuilder(new String[] { "cmd.exe" });
		process = builder.start();

		OutputStream os = process.getOutputStream();

		StreamReader errorReader = new StreamReader(process.getErrorStream(),"ERROR",true,true);
		StreamReader inputReader = new StreamReader(process.getInputStream(),"INPUT",true,false);
		errorReader.start();
		inputReader.start();
		os.write("@echo off\n".getBytes());
	    os.flush();
	   // Thread.sleep(100);
	   
	    for (int i = 0; i < cmds.length; i++) {
	    	if(i==cmds.length-1) {
	    	  Thread.sleep(500);
	 	      inputReader.setStartCaching(true);		 	     	     
	    	}
	    	os.write((cmds[i]+"\n").getBytes());
	    	os.flush();
		}
     		    
	    os.close();
    	process.waitFor();

        result = errorReader.getResult();
        errorReader.dispose();
	    if(check4Error()) {
			inputReader.dispose();
	        throw new ClearCaseException(result);
	    }
		result = inputReader.getResult();
		System.out.println("prabhatk: "+this.getClass().getName()+" RESULT "+result);
		 
		inputReader.dispose();
		
		return filterOutput();
	}
	
	private boolean check4Error() {
		return result.trim().startsWith("cleartool:");
	}
	
	public final void start(Object payload) {
		clear();
		clearRepositoryMap();
		try {
			populate(payload);
		} catch (IOException e) {
			e.printStackTrace();
			Util.showMessage(e.getMessage(), "IO Exception ", SWT.ERROR|SWT.OK);
		} catch (InterruptedException e) {
			e.printStackTrace();
			Util.showMessage(e.getMessage(), " InterruptedException ", SWT.ERROR|SWT.OK);
		} catch (ClearCaseException e) {
			Util.showMessage(e.getMessage(), "ClearCase Error", SWT.ERROR|SWT.OK);
		}
	}
	
	
	private void clearRepositoryMap() {
		UtilRepository.clearMap(getRepositoryType());
	}
	
	protected abstract void populate(Object payload) throws IOException, InterruptedException, ClearCaseException;
	
	protected int getRepositoryType() {
		return -1;
	}
			
	protected abstract String filterOutput();
}
